﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ObservadorPeplau.API;
using ObservadorPeplau.API.Business;

namespace ObservadorPeplau.Usercontrols
{
    public partial class CommentDetails : UserControl
    {
        private readonly Dictionary<string, Image> _imageBuffer = new Dictionary<string, Image>();

        private BackgroundWorker _currentWorker;
        public Comment Comment { get; private set; }

        public CommentDetails()
        {
            InitializeComponent();
        }

        private void CommentDetails_Load(object sender, EventArgs e)
        {
        }

        private void imageBgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            var url = e.Argument.ToString();

            if (_imageBuffer.ContainsKey(url))
            {
                picAuthor.Image = _imageBuffer[url];
                return;
            }

            // Load Image from URL
            picAuthor.Image = null;
            var loadedImage = ImageManager.LoadImageFromUrl(url);
            if (sender == _currentWorker)
                picAuthor.Image = loadedImage;

            // Save on Buffer for future reusing
            _imageBuffer.Add(url, loadedImage);
        }

        private void LoadImageAsync(string url)
        {
            var bgWorker = new BackgroundWorker();
            bgWorker.DoWork += imageBgWorker_DoWork;
            _currentWorker = bgWorker;
            _currentWorker.RunWorkerAsync(url);
        }

        public void LoadComment(Comment comment)
        {
            Comment = comment;

            if (comment==null)
            {
                picAuthor.Image = null;
                labAuthor.Text = "";
                labDateTime.Text = "";
                txbComment.Text = "";
                return;
            }

            LoadImageAsync(comment.Author.ImageUrl);

            labAuthor.Text = comment.Author.Name;
            labDateTime.Text = comment.DateTime.ToShortDateString() + " às " + comment.DateTime.ToShortTimeString();
            txbComment.Text = comment.TextWithoutHtml;
        }
    }
}
